package com.frt.sygang.controller;
/*
 * Created by 冯瑞涛 on 2022/9/18 19:08
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frt.sygang.common.R;
import com.frt.sygang.entity.dto.DishDto;
import com.frt.sygang.entity.Category;
import com.frt.sygang.entity.Dish;
import com.frt.sygang.entity.DishFlavor;
import com.frt.sygang.sevice.CategoryService;
import com.frt.sygang.sevice.DishFlavorService;
import com.frt.sygang.sevice.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 冯瑞涛
 * @version 1.0
 * @date 2022/9/18 19:08
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

/*
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CacheManager cacheManager;
*/

    /**
     * 分页查询方法
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<IPage> pageQueryDish(Integer page, Integer pageSize, String name) {
        //声明分页对象
        IPage<Dish> iPage = new Page(page, pageSize);
        //声明数据传输对象分页对象
        IPage<DishDto> dtoPage = new Page(page, pageSize);
        //声明条件对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询条件添加
        queryWrapper.like(!StringUtils.isEmpty(name), Dish::getName, name);
        //调用菜品分页查询方法进行菜品信息分页查询
        dishService.page(iPage, queryWrapper);

        //将查询出的分页查询对象的属性值复制给数据传输分页对象（除records数据外;
        BeanUtils.copyProperties(iPage, dtoPage, "records");
        //将分页对象中的数据取出未一个数据集合
        List<Dish> records = iPage.getRecords();
        //使用stream流将集合中的单个对象取出
        List<DishDto> dishDtos = records.stream().map(temp -> {
            //取出对象的分类id属性
            Long categoryId = temp.getCategoryId();
            //根据分类id查分类
            Category byId = categoryService.getById(categoryId);
            //声明数据传输对象
            DishDto dishDto = new DishDto();
            //将菜品对象的属性值复制给数据传输对象
            BeanUtils.copyProperties(temp, dishDto);
            if (byId != null) {
                //将查询出的分类信息的分类名属性复制给数据传输对象
                dishDto.setCategoryName(byId.getName());
            }
            //返回数据传输对象
            return dishDto;
            //将处理后的结果做转为一个集合
        }).collect(Collectors.toList());
        //将集合赋值给dto传输对象的数据属性
        dtoPage.setRecords(dishDtos);
        return R.success(dtoPage);
    }

    /**
     * 添加菜品信息和相关口味信息方法
     *
     * @param dishDto 新增的菜品信息
     * @return
     */
    @CacheEvict(value = "dishCache", key = "'dish_'+#dishDto.categoryId+'_1'")
    @PostMapping
    public R<String> insDishAndFlavor(@RequestBody DishDto dishDto) {
//        String key="dish_"+dishDto.getCategoryId()+"_1";
        dishService.insDishAndFlavor(dishDto);
//        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    /**
     * 根据id回返菜品信息方法
     *
     * @param id 菜品id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> backDishById(@PathVariable Long id) {
        DishDto dishDto = dishService.backDishDto(id);
        if (dishDto != null) {
            return R.success(dishDto);
        }
        return R.error("未查询到菜品信息，请更新后再试");
    }

    /**
     * 修改菜品信息方法
     *
     * @param dishDto 目标数据传输对象
     * @return
     */
    @CacheEvict(value = "dishCache", key = "'dish_'+#dishDto.categoryId+'_1'")
    @PutMapping
    public R<String> setDishAndFlavor(@RequestBody DishDto dishDto) {
        log.info(dishDto.getCategoryId().toString());
//        String key="dish_"+dishDto.getCategoryId()+"_1";
        dishService.setDishAndFlavor(dishDto);
//        redisTemplate.delete(key);
        return R.success("修改一下");
    }

    /**
     * 批量修改产品状态
     *
     * @param value 目标状态值
     * @param ids   需要修改的id数组
     * @return
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping("/status/{value}")
    public R<String> setStatus(@PathVariable("value") Integer value, Long[] ids) {
        //创建修改条件对象
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        //将id数组转换为集合
        List<Long> dishIds = Arrays.asList(ids);
        //设置需要修改的属性和设置需修改的范围
        updateWrapper.set(Dish::getStatus, value).in(Dish::getId, dishIds);
        //调用修改方法将修改条件对象作为参数传入
        dishService.update(updateWrapper);
        //设置成功信息
        String massage = value == 1 ? "启售成功" : "禁售成功";
        //返回设置成功信息
        return R.success(massage);
    }

    /**
     * 删除菜品方法
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @DeleteMapping
    public R<String> deleteDish(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        dishService.deleteDish(list);
        return R.success("删除成功");
    }

    /**
     * 根据分类id获取菜品方法
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "dishCache", key = "'dish_'+#dish.categoryId+'_'+#dish.status", unless = "#result==null")
    @GetMapping("/list")
    public R<List<DishDto>> backDishByCategoryId(Dish dish) {
        List<DishDto> dishDtos = null;
//        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
//        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        if (dishDtos != null) {
//            return R.success(dishDtos);
//        }
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        List<Dish> list = dishService.list(wrapper);
        dishDtos = list.stream().map(temp -> {
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            DishDto dishDto = new DishDto();
            Long id = temp.getId();
            queryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            BeanUtils.copyProperties(temp, dishDto);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
//        redisTemplate.opsForValue().set(key,dishDtos);
        return R.success(dishDtos);
    }
}
